<?php

namespace App\Console\Commands\Elasticsearch;

use Illuminate\Console\Command;
use File;
use Illuminate\Support\Collection;
use Illuminate\Contracts\Container\BindingResolutionException;

/**
 * 生成索引
 * @package App\Console\Commands
 */
class EsCreateIndex extends Command
{
    use Common;
    protected $signature = 'es:create-index {module}';

    protected $description = '生成模型索引';

    protected $module;

    public function __construct()
    {
        parent::__construct();
    }

    public function handle()
    {
        $this->module = $this->argument('module');

        $this->makeEsIndex();
    }

    /**
     * 创建索引
     * @return void
     * @throws BindingResolutionException
     */
    protected function makeEsIndex()
    {
        $this->getModels()->each(function ($class) {

            $indexName = $this->getIndexNameByModelClass($class);

            $reflectionMethod = new \ReflectionMethod($class, 'elasticsearchMapping');
            $mapping = $reflectionMethod->invoke(new $class, 'elasticsearchMapping');

            $params = [
                'index' => $indexName,
                'body' => [
                    'mappings' => [
                        'properties' => $mapping
                    ]
                ]
            ];
            $this->info("正在创建【{$indexName}】索引 ");
            if (app('es')->indices()->exists(['index' => $indexName])) {
                $this->info("索引【{$indexName}】已经存在，本次没有操作");
                return;
            }
            app('es')->indices()->create($params);
        });

        $this->info("所有索引创建完毕");
    }
}
